/*
 * @Descripttion:
 * @version:
 * @Author: kl2018
 * @Date: 2018-12-17 09:11:31
 * @LastEditors: kl2018
 * @LastEditTime: 2020-10-29 11:03:51
 */

import React, { PureComponent } from 'react';
import { WeaNewScroll, WeaTab, WeaLocaleProvider, WeaFormItem } from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import { inject, observer } from 'mobx-react';
import { Button } from 'antd';
import { toJS } from 'mobx';

const { getLabel } = WeaLocaleProvider;

@inject('tabComponentStore')
@observer
class TabComponent extends PureComponent {
  /*
    getDataList  获取列表数据方法
    baseSearchName  基础搜索的name
    searchType  搜索类型
    tabUrl tab页签的接口
    getFormUrl 获取高级搜索form表单的接口
    searchCustomRender 自定义渲染的方法   自定义渲染示例查看  SearchReqComponent.js
    tabKey 切换tab页签 参数
    searchParams 获取高级搜索所需的参数
    tabParams 获取tab所需要的参数
    selectedTabKey 设置tab的selectedKey
    moreTimeGetCondition 是否多次获取conditions false | true
    changeTabFun 改变页签需要执行的方法
    canGetTableData 是否获取高级搜索和获取列表分开获取

    !!! getDataList的参数onlyParams, covered, saveParams 为了兼容BaseTableCom
        只使用TabComponent 不用管这三个参数
  */

  constructor(props) {
    super(props);
    const { showSearchGroup = false, searchType } = props;
    this.onClickSearchBtn = this.onClickSearchBtn.bind(this);
    this.getTabData = this.getTabData.bind(this);
    this.searchType = showSearchGroup ? ['advanced'] : searchType;
    this.leftStyle = { width: 'calc(100% - 250px)' };
  }

  componentDidMount () {
    const { getFormUrl = '', tabComponentStore, tabUrl = '', searchCustomRender, searchParams = {}, tabParams = {}, selectedTabKey = '0',
      initGetTabData = true, initGetForm = true, baseSearchName } = this.props;
    if (getFormUrl != '') {
      const isCustomRender = !!searchCustomRender;
      initGetForm && tabComponentStore.getSearchFormItem(getFormUrl, searchParams, baseSearchName, isCustomRender);
    }
    tabComponentStore.setMobxState({ selectedKey: selectedTabKey, tabParams });
    tabUrl && initGetTabData && this.getTabData(tabUrl, tabParams);
  }

  componentWillUnmount () {
    const { tabComponentStore } = this.props;
    tabComponentStore.initData();
  }

  render () {
    const { tabComponentStore, showSearchGroup = false } = this.props;
    const { showSearchAd, setShowSearchAd, tabData, selectedKey, topTabCount,
      searchValue, searchForm, items } = tabComponentStore;
    const length = items && toJS(items).length || 0;
    const searchGroupHeight = length > 4 ? '148px' : length > 0 ? '74px' : '0px';
    return (
      <div className="odoc-tabCom">
        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@2mowj1`}
          datas={toJS(tabData)}
          counts={toJS(topTabCount)}
          selectedKey={selectedKey || '0'}
          keyParam="viewcondition"
          countParam="groupid"
          onChange={this.changeTab}
          showSearchAd={showSearchAd}
          setShowSearchAd={setShowSearchAd}
          buttonsAd={this.getSearchFormButtons()}
          searchsAd={this.getSearchForm()}
          advanceHeight={'auto'}
          onSearch={this.onSearch}
          searchsBaseValue={searchValue}
          onSearchChange={this.synSearchsBaseValue}
          leftStyle={this.leftStyle}
          {...this.props}
          searchType={this.searchType}
        />

        {
          showSearchGroup && !showSearchAd && length > 0 &&
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@mvkuha`} type="primary" className="searchBtn" onClick={() => this.onClickSearchBtn({}, false, false)}>{getLabel(387355, '搜索')}</Button>
        }

        {
          showSearchGroup &&
          <div className="odoc-tabCom-searchGroup" style={{ height: searchGroupHeight }}>
            <div className="odoc-tabCom-searchGroup-items">
              {
                searchForm.isFormInit &&
                items.map(field => (
                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@wqzvea@${field.domkey[0]}`}
                    label={`${field.label}`}
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                  >
                    <WeaSwitch
                      ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@2sw0rt@${field.domkey[0]}`}
                      fieldConfig={field}
                      form={searchForm}
                      onChange={this.onChange}
                      onBlur={this.onBlur}
                      onEnterSearch={this.onEnterSearch}
                    />
                  </WeaFormItem>
                ))
              }
            </div>
          </div>
        }
      </div>
    );
  }

  // 获取搜索框
  getSearchForm () {
    const { tabComponentStore, searchCustomRender } = this.props;
    const { searchForm, conditions, setShowSearchAd } = tabComponentStore;
    const func = {
      onChange: this.onChange,
      onBlur: this.onBlur,
      closeSearch: () => setShowSearchAd(false),
    }
    if (searchCustomRender) {
      return searchCustomRender(searchForm, toJS(conditions), func);
    }
    return (
      <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@rdmn4s`} ref="scroll" className="newUnit">
        {
          searchForm.render(
            { needTigger: true },
            {
              onChange: this.onChange,
              onBlur: this.onBlur,
              onEnterSearch: this.onEnterSearch,
            },
          )
        }
      </WeaNewScroll>
    );
  }

  // 获取高级搜索框的操作按钮
  getSearchFormButtons () {
    const { tabComponentStore, tabKey, baseSearchName } = this.props;
    const { searchForm, setShowSearchAd, selectedKey, searchValue } = tabComponentStore;
    let formData = searchForm.getFormParams();
    if (baseSearchName) {
      formData[baseSearchName] = searchValue;
    }
    if (tabKey) {
      formData[tabKey] = selectedKey;
    }
    const searchbutton = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ci89ds@search`} type="primary" onClick={() => this.onClickSearchBtn({}, false, false)}>{getLabel(387355, '搜索')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jkh3if@reset`} type="ghost" onClick={this.resetForm}>{getLabel(2022, '重置')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bx39l3@cancel`} type="ghost" onClick={() => setShowSearchAd(false)}>{getLabel(31129, '取消')}</Button>,
    ];
    return searchbutton;
  }

  // 基础搜索和form表单搜索同步
  synSearchsBaseValue = (v) => {
    const { tabComponentStore, baseSearchName } = this.props;
    const { searchForm, setMobxState } = tabComponentStore;
    const formParams = searchForm.getFormParams();
    if (formParams[baseSearchName] != undefined) {
      let obj = {};
      obj[baseSearchName] = { value: v };
      searchForm.updateFields(obj, false);
      setMobxState({ searchValue: v });
    } else {
      setMobxState({ searchValue: v });
    }
  }

  // 改变页签是触发函数
  changeTab = (key) => {
    const { getDataList, tabComponentStore, tabKey, baseSearchName, getFormUrl = '', moreTimeGetCondition = false,
      searchCustomRender, searchParams = {}, changeTabFun } = this.props;
    const { searchForm, fastForm, searchValue } = tabComponentStore;
    let params = {
      ...searchForm.getFormParams(),
      ...fastForm.getFormParams(),
    };
    if (tabKey) {
      params[tabKey] = key;
      let tabKeyParams = {};
      tabKeyParams[tabKey] = key;
    }
    if (baseSearchName) {
      params[baseSearchName] = searchValue;
    }
    tabComponentStore.selectedKey = key;

    !changeTabFun && getDataList(params);
    changeTabFun && changeTabFun(key, params);

    if (moreTimeGetCondition) {
      if (getFormUrl != '') {
        if (tabKey) {
          searchParams[tabKey] = key;
        }
        const isCustomRender = !!searchCustomRender;
        tabComponentStore.getSearchFormItem(getFormUrl, searchParams, baseSearchName, isCustomRender);
      }
    }
  }

  // 普通搜索框搜索
  onSearch = (text) => {
    const { getDataList, baseSearchName, tabComponentStore, tabKey } = this.props;
    const { selectedKey, searchForm, fastForm } = tabComponentStore;
    let searchParams = {
      ...searchForm.getFormParams(),
      ...fastForm.getFormParams()
    };
    if (tabKey) {
      searchParams[tabKey] = selectedKey;
    }
    if (!baseSearchName) {
      getDataList(searchParams, false, false);
    } else {
      searchParams[baseSearchName] = text;
      getDataList(searchParams, false, false);
    }
  }

  onChange = (data) => {
    const { baseSearchName, tabComponentStore, showSearchGroup } = this.props;
    const { setMobxState, fastForm, searchForm, items } = tabComponentStore;
    const itemLength = items && toJS(items).length || 0;
    const fieldKey = Object.keys(data)[0];
    if (typeof data[fieldKey].value != "string" || Object.keys(data[fieldKey]).length > 1) {
      const hasSomeField = Object.hasOwnProperty.call(fastForm.getFormParams(), fieldKey) && Object.hasOwnProperty.call(searchForm.getFormParams(), fieldKey);
      if (showSearchGroup && itemLength > 0 && hasSomeField) {
        fastForm.updateFields(data);
        searchForm.updateFields(data);
      }
    };
    if (data[baseSearchName]) {
      setMobxState({ searchValue: data[baseSearchName].value });
    }
  }

  onBlur = (values1, values2) => {
    const { tabComponentStore, showSearchGroup } = this.props;
    const { fastForm, searchForm, items } = tabComponentStore;
    const itemLength = items && toJS(items).length || 0;
    const value = typeof values1 == 'object' ? values1 : values2;
    const fieldKey = Object.keys(value)[0];
    const hasSomeField = Object.hasOwnProperty.call(fastForm.getFormParams(), fieldKey) && Object.hasOwnProperty.call(searchForm.getFormParams(), fieldKey);
    if (showSearchGroup && itemLength > 0 && hasSomeField) {
      fastForm.updateFields(value);
      searchForm.updateFields(value);
    }
  }

  // 外抛获取页签的方法
  getTabData (
    // params
  ) {
    const { tabComponentStore, tabUrl = '', tabParams = {} } = this.props;
    if (tabUrl != '') {
      tabComponentStore.getTabData(tabUrl, tabParams);
    }
  }

  // 外抛获取form的方法
  getSearchFormItem (otherParams) {
    const { tabComponentStore, getFormUrl, searchParams = {}, searchCustomRender, tabKey, baseSearchName } = this.props;
    if (getFormUrl != '') {
      if (tabKey) {
        searchParams[tabKey] = tabComponentStore.selectedKey;
      }
      const isCustomRender = !!searchCustomRender;
      return tabComponentStore.getSearchFormItem(getFormUrl, { ...otherParams, ...searchParams }, baseSearchName, isCustomRender);
    }
  }

  // 高级搜索 onlyParams, covered, saveParams 为了兼容BaseTableCom
  onClickSearchBtn (params = {}, onlyParams, covered, saveParams) {
    const { getDataList, tabComponentStore, tabUrl, tabKey, baseSearchName } = this.props;
    const { searchForm, fastForm, selectedKey, searchValue } = tabComponentStore;
    let formParams = {
      ...searchForm.getFormParams(),
      ...fastForm.getFormParams(),
    };
    if (tabUrl && tabKey) {
      formParams[tabKey] = selectedKey;
    }
    if (baseSearchName) {
      formParams[baseSearchName] = searchValue;
    }
    formParams = {
      ...formParams,
      ...params,
    };
    getDataList(formParams, onlyParams, covered, saveParams);
    tabComponentStore.setShowSearchAd(false);
  }

  resetForm = () => {
    const { tabComponentStore } = this.props;
    const { searchForm, setMobxState, fastForm, conditions, fastFormConditions } = tabComponentStore;
    searchForm.resetForm(); // 因为清空不了日期组件（组件库不改） 所以换成了initFormFields
    fastForm.resetForm(); // 因为清空不了日期组件（组件库不改） 所以换成了initFormFields
    // searchForm.initFormFields(toJS(conditions));
    // fastForm.initFormFields(toJS(fastFormConditions));
    setMobxState({ searchValue: '' });
  }

  changeFields (obj) {
    const { tabComponentStore } = this.props;
    tabComponentStore.searchForm.updateFields(obj, false);
  }

  // 外抛搜索条件
  getFormParams () {
    const { baseSearchName, tabComponentStore, tabKey } = this.props;
    const { selectedKey, searchForm, searchValue } = tabComponentStore;
    let searchParams = searchForm.getFormParams();
    if (tabKey) {
      searchParams[tabKey] = selectedKey;
    }
    if (!baseSearchName) {
    } else {
      searchParams[baseSearchName] = searchValue;
    }
    return searchParams;
  }

  onEnterSearch = () => this.onClickSearchBtn({}, false, false)
}

export default TabComponent;
